package com.ysw.advice;

import com.ysw.constant.ServiceCodeStatus;
import com.ysw.dto.ResponseResult;
import com.ysw.exception.ServiceException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理器
 * @Author ysw
 * @Date 2022/5/12 18:50
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理指定异常
     * @param request
     * @param exception
     * @return
     */
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = {RuntimeException.class})
    public ResponseResult handleBindException(HttpServletRequest request, Exception exception) {
        return ResponseResult.fail(ServiceCodeStatus.ERROR);
    }

    /**
     * 处理业务异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = {ServiceException.class})
    public ResponseResult handleServiceException(HttpServletRequest request, Exception exception) {
        ServiceException serviceException = (ServiceException) exception;
        return ResponseResult.fail(serviceException.getCodeStatus());
    }
}